package com.sjm.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sjm.demo.pojo.TestUser;
import com.sjm.demo.mapper.TestUserMapper;
import com.sjm.demo.service.TestUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.sjm.demo.utils.DingUtil.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sjm
 * @since 2021-03-12
 */
@Slf4j
@Service
public class TestUserServiceImpl extends ServiceImpl<TestUserMapper, TestUser> implements TestUserService {

    @Value("${ding.ding.appId}")
    private String appId;

    @Value("${ding.ding.appSecret}")
    private String appSecret;

    @Value("${ding.ding.redirectUri}")
    private String redirectUri;

    @Override
    public String getUnionidByCode(String code) {
        try {
            return getUnionid(code, appId, appSecret);
        } catch (ApiException e) {
            log.error("获取unionid错误:{}", e.getErrMsg());
        }
        return null;
    }

    @Override
    public String getUserInfoByCode(String code) {
        try {
            System.out.println("code:"+code+"appId:"+appId+"appSecret:"+appSecret);
            return getUserInfo(code, appId, appSecret);
        } catch (ApiException e) {
            log.error("获取userInfo错误:{}", e.getErrMsg());
        }
        return null;
    }

    @Override
    public String getAccessTokenByAppIdAndSecret() {
        return getToken(appId, appSecret);
    }

    @Override
    public String getUserId(String unionid, String token) {
        try {
            return getUserIdByUnionid(unionid,token);
        } catch (ApiException e) {
            log.error("获取useId错误:{}", e.getErrMsg());
        }
        return null;
    }

    @Override
    public Object getUserInfoByUserId(String userId, String token) {
        try {
            return getUserInfo(userId,token);
        } catch (ApiException e) {
            log.error("获取userInfo错误:{}", e.getErrMsg());
        }
        return null;
    }

    @Override
    public JSONObject getAppIdAndRedirectUri() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appid",appId);
        jsonObject.put("redirectUri",redirectUri);
        return jsonObject;
    }
}
